using System.Globalization;
using System.Web;
using Framework.Library.Core.Utils.Web;

namespace Framework.Library.Core.Utils.Miscellaneous
{
    public static class HttpUtilities
    {
        public static string GetCompleteUrlPath(HttpContext context, string pageUrl)
        {
            if (string.IsNullOrEmpty(pageUrl))
                return string.Empty;


            if (UrlUtils.IsRelativeUrl(pageUrl))
                pageUrl = VirtualPathUtility.Combine(context.Request.ApplicationPath, pageUrl);

            return pageUrl;
        }

        public static bool AccessingPage(HttpContext context, string pageUrl)
        {
            if (!string.IsNullOrEmpty(pageUrl))
            {
                pageUrl = GetCompleteUrlPath(context, pageUrl);

                if (string.IsNullOrEmpty(pageUrl))
                    return false;

                int queryStartIndex = pageUrl.IndexOf('?');
                if (queryStartIndex >= 0)
                    pageUrl = pageUrl.Substring(0, queryStartIndex);

                string requestPath = context.Request.Path;

                if (string.Compare(requestPath, pageUrl, true, CultureInfo.InvariantCulture) == 0)
                    return true;

                if (pageUrl.IndexOf('%') >= 0)
                {
                    string decodedUnlockUrl = HttpUtility.UrlDecode(pageUrl);
                    if (string.Compare(requestPath, decodedUnlockUrl, true, CultureInfo.InvariantCulture) == 0)
                        return true;

                    decodedUnlockUrl = HttpUtility.UrlDecode(pageUrl, context.Request.ContentEncoding);
                    if (string.Compare(requestPath, decodedUnlockUrl, true, CultureInfo.InvariantCulture) == 0)
                        return true;
                }
            }
            return false;
        }
    }
}